#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import RPi.GPIO as GPIO
import time
import math

import Adafruit_DHT
speed_min = 20
speed = 100
temperature_start = 18000
temperature_max = 35000
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT)
GPIO.setup(23,GPIO.OUT)
GPIO.output(18, 1)
GPIO.output(23, 0)
GPIO.setwarnings(False)
pwm = GPIO.PWM(23,100)
pwm1 = GPIO.PWM(18,100)
pwm.start(0.5)
HC_SR501 = 5
GPIO.setmode(GPIO.BCM)
GPIO.setup(HC_SR501,GPIO.IN)

class DHT11:
    def DHT11_Read(self):
        sensor = Adafruit_DHT.DHT11
        gpio = 26
        humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
        return humidity,temperature

def getSpeed(tem):
    speed1 = int(-6*tem + 190)
    if(speed1>80):
        return 80
    elif speed1<0:
        return 1
    else:
        return speed1



if __name__ == '__main__':
    humid = 0
    temp = 0
    dht11 = DHT11()
    while True:
        flag = GPIO.input(HC_SR501)
        if flag:            
            print("you ren ,qidong!")
            humid,temp=dht11.DHT11_Read()
            pwm.ChangeDutyCycle(100)
            if(temp is not None):
                speed12 = getSpeed(temp)
                pwm.ChangeDutyCycle(speed12)
                print(speed12)
                time.sleep(5)
            if humid is not None and temp is not None:
                    print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temp, humid))
            else:
                print('Failed to get reading. Try again!')

        else:
            print("wu ren!")
            pwm.ChangeDutyCycle(100)
            time.sleep(2)
            
            

